﻿using XfTechOAWeb.Data;
using XfTechOAWeb.IService;
using XfTechOAWeb.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XfTechOAWeb.Dtos;
using XfTechOAWeb.Dtos.Roles;
using XfTechOAWeb.Data.Base;

namespace XfTechOAWeb.Service
{
    public class RoleService : IRoleService
    {
        IRoleRepository _roleRepository;
        IRepository<RolePermission> _rolePermissionRepository;

        public RoleService(IRoleRepository roleRepository, IRepository<RolePermission> rolePermissionRepository)
        {
            _roleRepository = roleRepository;
            _rolePermissionRepository = rolePermissionRepository;
        }

        public int Add(RoleAddDto role)
        {
            Role role1 = new Role()
            {
                CreatedTime = DateTime.Now,
                RName=role.RName,
                RText=role.RText,
                Status=role.Status,
            };
            _roleRepository.Insert(role1);
            return _roleRepository.SaveChanges();
        }

        //批删
        public int Del(string ids)
        {
            string[] arrId = ids.Split(',');
            foreach (var id in arrId)
            {
                _roleRepository.Remove(Convert.ToInt32( id));
            }

            return _roleRepository.SaveChanges();
        }

        public PageResponseModel<Role> Show(RoleFindPageDto findPage)
        {
            var query = from s in _roleRepository.Table
                        where (string.IsNullOrEmpty(findPage.name) || s.RName.Contains(findPage.name))
                        orderby s.RId
                        select s;

            PageResponseModel<Role> page = new PageResponseModel<Role>()
            {
                TotalCount = query.Count(),
                PageList = query.Skip((findPage.pageIndex - 1) * findPage.pageSize).Take(findPage.pageSize).ToList()
            };

            return page;
        }

        public int Upt(Role role)
        {
           
            _roleRepository.Update(role);
            return _roleRepository.SaveChanges();
        }

        /// <summary>
        /// 获取角色对应的权限
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public List<int> GetRolePermission(int rid)
        {
            var PermissionId = from rolePermission in _roleRepository.GetRolePermissions(rid)
                               select new
                               {
                                   pid = rolePermission.PermissionId
                               };
            List<int> ids = new List<int>();
            foreach (var id in PermissionId)
            {
                int pId = id.pid;
                ids.Add(pId);
            }
            return ids;
        }

        /// <summary>
        /// 获取角色对应的Id
        /// </summary>
        /// <param name="rid"></param>
        /// <returns></returns>
        public List<int> GetRoleUser(int rid)
        {
            var query = from roleUsers in _roleRepository.GetRoleUsers(rid)
                         select roleUsers.UserId;
            
            return query.ToList();
        }

        /// <summary>
        /// 获取所有的权限 （以层级结构的数据集合返回）
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        //public List<PermissionTreeDto> PTree(int pid=0)
        //{
        //    var list = _permissionRepository.Table.ToList(); //读出表中的所有权限数据

        //    return GetTree(list, pid);
        //}

        ////递归方法 拼接 树
        //private List<PermissionTreeDto> GetTree(List<Permission> permissions, int pid)
        //{
        //    //查询父Id下面的所有数据
        //    var list = _permissionRepository.Table.Where(x => x.ParentId == pid).ToList();
        //    if (list.Count == 0)
        //        return null;

        //    List<PermissionTreeDto> tos = new List<PermissionTreeDto>();
        //    list.ForEach(x =>
        //    {
        //        var node = new PermissionTreeDto()
        //        {
        //            PId = x.PId,
        //            PTitle = x.PTitle,
        //            ParentId = x.ParentId,
        //            PAction = x.PAction,
        //            Children = GetTree(permissions, x.PId)
        //        };

        //        tos.Add(node);
        //    });

        //    return tos;
        //}

        public int AddRolePermission(int rid, string pid)
        {
            return _roleRepository.AddRolePermission(rid, pid);
        }

        public List<RolePermission> GetTreePermission(int Rid)
        { 
            //1、获取角色权限表所有数据并进行linq查询
            List<RolePermission> rolePermissions= _rolePermissionRepository.Table.Where(x=>x.RoleId.Equals(Rid)).ToList();
            return rolePermissions;
        }
        /// <summary>
        /// 角色名唯一验证
        /// </summary>
        /// <param name="RName"></param>
        /// <returns></returns>
        public ResponseModel<string> UniqueRName(string RName)
        {
            var obj = _roleRepository.Table.Where(x=>x.RName.Equals(RName)).ToList();
            
            if (obj.Count==0)
            {
                ResponseModel<string> response = new ResponseModel<string>()
                {
                    Code = 200,
                    Data = null,
                    Msg="该角色名是唯一"
                };
                return response;
            }
            else
            {
                ResponseModel<string> response = new ResponseModel<string>()
                {
                    Code = 200,
                    Data = null,
                    Msg = "角色名重复"
                };

                return response;
            }
        }
    }
}
